package org.example.mynote.service.Impl;

import org.example.mynote.Entity.Note;
import org.example.mynote.Entity.Notebook;
import org.example.mynote.Entity.User;
import org.example.mynote.mapper.NoteMapper;
import org.example.mynote.mapper.NotebookMapper;
import org.example.mynote.mapper.UserMapper;
import org.example.mynote.service.NoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

import static org.springframework.http.HttpStatus.FORBIDDEN;
import static org.springframework.http.HttpStatus.NOT_FOUND;

@Service
public class NoteServiceImpl implements NoteService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private NoteMapper noteMapper;
    @Autowired
    private NotebookMapper notebookMapper;

    @Override
    public Note createNote(Long notebookId, String title, String content) {
        User currentUser = getCurrentUser();
        // 1. 验证笔记本是否存在且属于当前用户
        verifyNotebookOwnership(notebookId, currentUser.getId());

        Note note = new Note();
        note.setNotebookId(notebookId);
        note.setTitle(title);
        note.setContent(content);

        noteMapper.insert(note);
        return note;
    }

    @Override
    public Note updateNote(Long id, String title, String content) {
        User currentUser = getCurrentUser();
        // 1. 验证笔记是否存在且属于当前用户
        Note note = verifyNoteOwnership(id, currentUser.getId());

        // 2. 更新并保存
        note.setTitle(title);
        note.setContent(content);
        noteMapper.update(note);
        return note;
    }

    @Override
    public void deleteNote(Long id) {
        User currentUser = getCurrentUser();
        // 1. 验证笔记是否存在且属于当前用户
        verifyNoteOwnership(id, currentUser.getId());

        // 2. 执行删除
        noteMapper.deleteById(id);
    }

    @Override
    public List<Note> searchNotes(String keyword) {
        User currentUser = getCurrentUser();
        return noteMapper.searchByTitle(currentUser.getId(), keyword);
    }

    @Override
    public List<Note> getNotesByNotebook(Long notebookId) {
        User currentUser = getCurrentUser();
        // 验证笔记本的所有权
        verifyNotebookOwnership(notebookId, currentUser.getId());
        return noteMapper.findByNotebookId(notebookId);
    }

    // 辅助方法：获取当前登录的用户实体
    private User getCurrentUser() throws UsernameNotFoundException {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return userMapper.findByUsername(username);
    }
    // 辅助方法：验证笔记本是否属于当前用户
    private void verifyNotebookOwnership(Long notebookId, Long userId) {
        Notebook notebook = (Notebook) notebookMapper.findById(notebookId)
                .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "未找到对应笔记本，ID为" + notebookId));
        if (!notebook.getUserId().equals(userId)) {
            throw new ResponseStatusException(FORBIDDEN, "无响应笔记本项目");
        }
    }

    // 辅助方法：验证笔记是否属于当前用户 (通过其所在的笔记本)
    private Note verifyNoteOwnership(Long noteId, Long userId) {
        Note note = (Note) noteMapper.findById(noteId)
                .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "未找到对应笔记本，ID为" + noteId));
        verifyNotebookOwnership(note.getNotebookId(), userId);
        return note;
    }
}
